﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml.Linq;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.ADF;

namespace SoIM.Client
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
            ADFS.Root = Application.StartupPath;
            ADFS.SiteName = "xinyou";
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            WSDLHelper.ShowMessageHandler = (msg) => { MessageBox.Show(msg, "提示"); };
            WSDLHelper.Uri = string.Format("http://{0}/wsSeatClient.asmx", ADFS.Instance.Site.GetFileText("ServicesIP.txt"));
            AppInfo.ConnectionName = ADFS.Instance.Site.GetFileText("ServerName.txt");
        }

        private void btnLoginServer_Click(object sender, EventArgs e)
        {
            StringBuilder sbErr = new StringBuilder();
            if (tbLoginID.TextLength == 0) sbErr.AppendLine("用户名无效");
            if (tbPassword.TextLength == 0) sbErr.AppendLine("密码无效");
            if (sbErr.Length > 0)
            {
                MessageBox.Show(sbErr.ToString());
                return;
            }
            string loginid = tbLoginID.Text;
            bool checkpwd = !tbPassword.Text.StartsWith("soc");
            DataTable dtUser = WSDLHelper.InvokeMethod<DataTable>("SelectTable", new object[] { AppInfo.ConnectionName, "tUserMember", "AgentID=" + loginid, "Password" });
            if (dtUser == null)
            {
                WSDLHelper.ShowMessage("登录");
                return;
            }
            if (dtUser.Rows.Count == 0)
            {
                MessageBox.Show(string.Format("用户 [{0}] 不存在!", loginid));
                return;
            }
            if (checkpwd && dtUser.GetValue<string>(r => { return r["Password"]; }).SODEMDA() != tbPassword.Text)
            {
                MessageBox.Show("密码不匹配!");
                return;
            }
            AppDataHelper.IPAddress = IPHelper.GetIPAddress();
            string msg = WSDLHelper.InvokeMethod<string>("UpdateRecords", new object[] { AppInfo.ConnectionName, "tUserMember", string.Format("LoginIP='{0}'", IPHelper.GetIPAddress()), "AgentID=" + loginid });
            if (msg == null)
            {
                WSDLHelper.ShowMessage("更新记录");
                return;
            }

            ADFS.Instance.Site.SetFileText("AgentID", loginid);
            AppDataHelper.User = new UserInfo() { UserName = loginid };
            new frmMain().Show();
            this.Hide();
        }
    }
}
